package com.cn.stock.service.Impl;

import com.cn.api.StockService;
import com.cn.dto.StockDTO;
import com.cn.stock.entity.Stock;
import com.cn.stock.mapper.StockMapper;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

@Component
@RestController
@RequestMapping("/api/stock")
public class StockServiceImpl implements StockService {

    @Resource
    StockMapper stockMapper;

    private Stock stock = new Stock();

    @Override
    @GetMapping("/findAll")
    public List<StockDTO> findAll(@RequestBody StockDTO stockDTO) {
        stock.setProductId(stockDTO.getProductTypeId());
        stock.setAvailableStock(stockDTO.getAvailableStock());
        stock.setEndTime(stockDTO.getEndTime());
        stock.setProductTypeId(stockDTO.getProductTypeId());
        stock.setStock(stockDTO.getStock());
        stock.setUseDate(stockDTO.getUseDate());
        return stockMapper.findAll(stock);
    }

    @Override
    @PostMapping(value = "/add")
    public int add(@RequestBody StockDTO stockDTO) {
        stock.setProductId(stockDTO.getProductTypeId());
        stock.setAvailableStock(stockDTO.getAvailableStock());
        stock.setEndTime(stockDTO.getEndTime());
        stock.setProductTypeId(stockDTO.getProductTypeId());
        stock.setStock(stockDTO.getStock());
        stock.setUseDate(stockDTO.getUseDate());
        return stockMapper.add(stock);
    }

    @Override
    @DeleteMapping(value = "/delete")
    public int delete(@RequestBody StockDTO stockDTO) {
        stock.setProductId(stockDTO.getProductTypeId());
        stock.setAvailableStock(stockDTO.getAvailableStock());
        stock.setEndTime(stockDTO.getEndTime());
        stock.setProductTypeId(stockDTO.getProductTypeId());
        stock.setStock(stockDTO.getStock());
        stock.setUseDate(stockDTO.getUseDate());
        return stockMapper.delete(stock);
    }

    @Override
    @PostMapping(value = "/update")
    public int update(@RequestBody StockDTO stockDTO) {
        StockDTO Stock = stockMapper.findByProductId(stockDTO.getProductTypeId());
        int nowStock = Stock.getAvailableStock();
        int change = stockDTO.getChange();
        if (nowStock+change < 0){
            return 0;
        }else {
            stockDTO.setAvailableStock(nowStock+change);
            stock.setProductId(stockDTO.getProductTypeId());
            stock.setAvailableStock(stockDTO.getAvailableStock());
            stock.setEndTime(stockDTO.getEndTime());
            stock.setProductTypeId(stockDTO.getProductTypeId());
            stock.setStock(stockDTO.getStock());
            stock.setUseDate(stockDTO.getUseDate());
            return stockMapper.update(stock);
        }
    }

    @Override
    @PostMapping(value = "/findByProductId")
    public StockDTO findByProductId(@RequestParam int productId) {
        return stockMapper.findByProductId(productId);
    }
}
